import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { parse as parseUrl } from 'node:url'

function createProxyPlugin() {
  return {
    name: 'dev-dynamic-proxy',
    configureServer(server) {
      server.middlewares.use(async (req, res, next) => {
        try {
          if (!req.url) return next()
          const { pathname, query } = parseUrl(req.url, true)

          if (pathname === '/proxy' && query && query.url) {
            const target = String(query.url)
            const response = await fetch(target)
            const html = await response.text()
            const baseUrl = new URL(target)

            const rewriteAttr = (content) => {
              return content
                .replace(/(src|href)=("|')(.*?)(\2)/gi, (_m, attr, q, val) => {
                  // ignore data:, blob:, javascript:, about:blank, mailto:, tel:
                  const lower = String(val).trim()
                  if (/^(data:|blob:|javascript:|about:|mailto:|tel:|#)/i.test(lower)) return `${attr}=${q}${val}${q}`
                  let abs
                  try { abs = new URL(lower, baseUrl).toString() } catch { abs = lower }
                  return `${attr}=${q}/proxy-asset?url=${encodeURIComponent(abs)}${q}`
                })
            }

            const rewritten = rewriteAttr(html)
            res.statusCode = 200
            res.setHeader('Content-Type', 'text/html; charset=utf-8')
            res.setHeader('Cache-Control', 'no-store')
            res.end(rewritten)
            return
          }

          if (pathname === '/proxy-asset' && query && query.url) {
            const target = String(query.url)
            const response = await fetch(target)
            if (!response.ok) {
              res.statusCode = response.status
              res.end(`Upstream error ${response.status}`)
              return
            }
            const ct = response.headers.get('content-type') || 'application/octet-stream'
            res.statusCode = 200
            res.setHeader('Content-Type', ct)
            res.setHeader('Cache-Control', 'no-store')
            // stream body
            if (response.body) {
              response.body.pipeTo(new WritableStream({
                write(chunk) { res.write(chunk) },
                close() { res.end() },
                abort() { try { res.end() } catch {} }
              }))
            } else {
              const buf = Buffer.from(await response.arrayBuffer())
              res.end(buf)
            }
            return
          }

          return next()
        } catch (err) {
          res.statusCode = 500
          res.end('Proxy error')
        }
      })
    }
  }
}

// https://vite.dev/config/
export default defineConfig({
  plugins: [vue(), createProxyPlugin()],
})
